package com.yj.util;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;

/**
 * Created by zhengguanyong on 2017/12/28.
 */
public class PostHttp {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        HttpClient httpClient = new HttpClient();
        String url = "http://hyfw.95306.cn/gateway/hywx/TrainWebClient/hwzz_uouii.action";
        PostMethod postMethod = new PostMethod(url);
        //设置head
        postMethod.setRequestHeader("Cookie","JSESSIONID=F38FD3439989CFF04490800609E1DA9A; lyIH6X7dHG=MDAwM2IyYWM3NDQwMDAwMDAwMjUwA1E6fiQxNTE0NDU5MTA0");
//   填入各个表单域的值
        NameValuePair[] data = {
                new NameValuePair("hwzz.yzm", "63FD155B6A364CB4BC1680C1F74B4B37"),
                new NameValuePair("hwzz.type", "1"),
                new NameValuePair("hwzz.carNo", "4881112"),
                new NameValuePair("hwzz.hph", ""),
                new NameValuePair("check_code", "9900")
        };
//   将表单的值放入postMethod中
        postMethod.setRequestBody(data);
//   执行postMethod
        int statusCode = 0;
        try {
            statusCode = httpClient.executeMethod(postMethod);
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
//   HttpClient对于要求接受后继服务的请求，象POST和PUT等不能自动处理转发
//   301或者302
        if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
            //   从头中取出转向的地址
            Header locationHeader = postMethod.getResponseHeader("location");
            String location = null;
            if (locationHeader != null) {
                location = locationHeader.getValue();
                System.out.println("The page was redirected to:" + location);
            }
            else {
                System.err.println("Location field value is null.");
            }
            return;
        } else {
            System.out.println("-----------");
            System.out.println(postMethod.getStatusLine());
            String str = "";
            try {
                str = postMethod.getResponseBodyAsString();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(str);
        }
        postMethod.releaseConnection();
        return ;
    }
}